<template>
  <view class="invite-share-container">
    <!-- 分享弹窗 -->
    <uni-popup ref="sharePopup" type="bottom" background-color="#fff">
      <view class="share-popup">
        <view class="popup-header">
          <view class="popup-title">分享邀请</view>
          <view class="popup-close" @click="closeShare">×</view>
        </view>
        
        <view class="share-content">
          <!-- 邀请码展示 -->
          <view class="invite-code-section">
            <view class="code-title">我的邀请码</view>
            <view class="code-display">
              <view class="code-text">{{ inviteCode }}</view>
              <button class="copy-code-btn" @click="copyInviteCode">复制</button>
            </view>
          </view>
          
          <!-- 二维码 -->
          <view class="qr-code-section" v-if="qrCodeDataUrl">
            <view class="qr-title">邀请二维码</view>
            <image 
              :src="qrCodeDataUrl" 
              class="qr-code"
              @longpress="saveQRCode"
            />
            <view class="qr-tip">长按保存二维码</view>
          </view>
          
          <!-- 分享选项 -->
          <view class="share-options">
            <view class="options-title">选择分享方式</view>
            <view class="options-grid">
              <view 
                v-for="(option, index) in shareOptions" 
                :key="index"
                class="option-item"
                @click="handleShare(option.type)"
              >
                <view class="option-icon">{{ option.icon }}</view>
                <view class="option-label">{{ option.label }}</view>
              </view>
            </view>
          </view>
          
          <!-- 分享文案预览 -->
          <view class="share-preview">
            <view class="preview-title">分享文案预览</view>
            <view class="preview-content">
              <view class="preview-text">{{ shareTitle }}</view>
              <view class="preview-desc">{{ shareDesc }}</view>
              <view class="preview-link">{{ shareUrl }}</view>
            </view>
            <button class="copy-content-btn" @click="copyShareContent">复制全部内容</button>
          </view>
        </view>
      </view>
    </uni-popup>
    
    <!-- 分享成功提示 -->
    <uni-popup ref="successPopup" type="center">
      <view class="success-popup">
        <view class="success-icon">✅</view>
        <view class="success-title">分享成功</view>
        <view class="success-desc">邀请链接已复制到剪贴板</view>
        <button class="success-btn" @click="closeSuccess">确定</button>
      </view>
    </uni-popup>
  </view>
</template>

<script>
export default {
  name: 'InviteShare',
  
  props: {
    inviteCode: {
      type: String,
      default: ''
    },
    qrCodeDataUrl: {
      type: String,
      default: ''
    },
    shareUrl: {
      type: String,
      default: ''
    },
    shareTitle: {
      type: String,
      default: '邀请好友，一起赚积分！'
    },
    shareDesc: {
      type: String,
      default: '我在使用这个超棒的打印服务，邀请你一起来体验！'
    }
  },
  
  data() {
    return {
      shareOptions: [
        { type: 'wechat', icon: '💬', label: '微信好友' },
        { type: 'moments', icon: '📱', label: '朋友圈' },
        { type: 'qq', icon: '🐧', label: 'QQ好友' },
        { type: 'qzone', icon: '🌟', label: 'QQ空间' },
        { type: 'weibo', icon: '📢', label: '微博' },
        { type: 'copy', icon: '📋', label: '复制链接' }
      ]
    }
  },
  
  methods: {
    /**
     * 显示分享弹窗
     */
    show() {
      this.$refs.sharePopup.open()
    },
    
    /**
     * 关闭分享弹窗
     */
    closeShare() {
      this.$refs.sharePopup.close()
    },
    
    /**
     * 复制邀请码
     */
    copyInviteCode() {
      this.copyText(this.inviteCode, '邀请码已复制')
    },
    
    /**
     * 保存二维码
     */
    saveQRCode() {
      if (!this.qrCodeDataUrl) {
        this.showError('二维码不存在')
        return
      }
      
      // #ifdef MP-WEIXIN
      uni.saveImageToPhotosAlbum({
        filePath: this.qrCodeDataUrl,
        success: () => {
          this.showSuccess('二维码已保存到相册')
        },
        fail: (error) => {
          console.error('保存二维码失败:', error)
          this.showError('保存失败，请检查相册权限')
        }
      })
      // #endif
      
      // #ifdef H5
      const link = document.createElement('a')
      link.download = 'invite-qrcode.png'
      link.href = this.qrCodeDataUrl
      link.click()
      this.showSuccess('二维码已下载')
      // #endif
      
      // #ifdef APP-PLUS
      // APP环境下的保存逻辑
      plus.gallery.save(this.qrCodeDataUrl, () => {
        this.showSuccess('二维码已保存到相册')
      }, (error) => {
        this.showError('保存失败')
      })
      // #endif
    },
    
    /**
     * 处理分享
     */
    handleShare(type) {
      // 记录分享行为
      this.recordShareAction(type)
      
      switch (type) {
        case 'wechat':
          this.shareToWechat()
          break
        case 'moments':
          this.shareToMoments()
          break
        case 'qq':
          this.shareToQQ()
          break
        case 'qzone':
          this.shareToQzone()
          break
        case 'weibo':
          this.shareToWeibo()
          break
        case 'copy':
          this.copyShareContent()
          break
        default:
          this.copyShareContent()
      }
    },
    
    /**
     * 记录分享行为
     */
    async recordShareAction(shareChannel) {
      try {
        const { recordShare } = await import('@/api/invitations.js')
        
        const shareData = {
          shareChannel,
          sharePlatform: this.getCurrentPlatform(),
          inviteCode: this.inviteCode
        }
        
        await recordShare(shareData)
      } catch (error) {
        console.error('记录分享行为失败:', error)
        // 不影响分享流程，静默处理错误
      }
    },
    
    /**
     * 获取当前平台
     */
    getCurrentPlatform() {
      // #ifdef MP-WEIXIN
      return 'miniprogram'
      // #endif
      
      // #ifdef H5
      return 'h5'
      // #endif
      
      // #ifdef APP-PLUS
      return 'app'
      // #endif
      
      return 'unknown'
    },
    
    /**
     * 分享到微信
     */
    shareToWechat() {
      // #ifdef MP-WEIXIN
      uni.showShareMenu({
        withShareTicket: true,
        success: () => {
          this.closeShare()
        }
      })
      // #endif
      
      // #ifdef H5
      if (this.isWechat()) {
        this.showTip('请点击右上角分享按钮')
        this.closeShare()
      } else {
        this.copyShareContent()
      }
      // #endif
      
      // #ifdef APP-PLUS
      this.shareToNative('wechat')
      // #endif
    },
    
    /**
     * 分享到朋友圈
     */
    shareToMoments() {
      // #ifdef MP-WEIXIN
      // 小程序不支持直接分享到朋友圈
      this.showTip('请先分享给微信好友，再转发到朋友圈')
      // #endif
      
      // #ifdef H5
      if (this.isWechat()) {
        this.showTip('请点击右上角分享到朋友圈')
        this.closeShare()
      } else {
        this.copyShareContent()
      }
      // #endif
      
      // #ifdef APP-PLUS
      this.shareToNative('moments')
      // #endif
    },
    
    /**
     * 分享到QQ
     */
    shareToQQ() {
      // #ifdef APP-PLUS
      this.shareToNative('qq')
      // #endif
      
      // #ifndef APP-PLUS
      this.copyShareContent()
      // #endif
    },
    
    /**
     * 分享到QQ空间
     */
    shareToQzone() {
      // #ifdef APP-PLUS
      this.shareToNative('qzone')
      // #endif
      
      // #ifndef APP-PLUS
      this.copyShareContent()
      // #endif
    },
    
    /**
     * 分享到微博
     */
    shareToWeibo() {
      // #ifdef APP-PLUS
      this.shareToNative('weibo')
      // #endif
      
      // #ifndef APP-PLUS
      this.copyShareContent()
      // #endif
    },
    
    /**
     * 原生分享
     */
    shareToNative(platform) {
      // #ifdef APP-PLUS
      const shareContent = {
        type: 'text',
        title: this.shareTitle,
        summary: this.shareDesc,
        href: this.shareUrl
      }
      
      plus.share.sendWithSystem(shareContent, () => {
        this.showSuccess('分享成功')
        this.closeShare()
      }, (error) => {
        console.error('分享失败:', error)
        this.showError('分享失败')
      })
      // #endif
    },
    
    /**
     * 复制分享内容
     */
    copyShareContent() {
      const content = `${this.shareTitle}\n\n${this.shareDesc}\n\n邀请链接：${this.shareUrl}`
      this.copyText(content, '分享内容已复制')
      this.closeShare()
      this.showShareSuccess()
    },
    
    /**
     * 复制文本
     */
    copyText(text, successMsg = '复制成功') {
      // #ifdef H5
      if (navigator.clipboard) {
        navigator.clipboard.writeText(text).then(() => {
          this.showSuccess(successMsg)
        }).catch(() => {
          this.fallbackCopy(text, successMsg)
        })
      } else {
        this.fallbackCopy(text, successMsg)
      }
      // #endif
      
      // #ifndef H5
      uni.setClipboardData({
        data: text,
        success: () => {
          this.showSuccess(successMsg)
        },
        fail: () => {
          this.showError('复制失败')
        }
      })
      // #endif
    },
    
    /**
     * 降级复制方法
     */
    fallbackCopy(text, successMsg) {
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      
      try {
        document.execCommand('copy')
        this.showSuccess(successMsg)
      } catch (err) {
        this.showError('复制失败，请手动复制')
      }
      
      document.body.removeChild(textArea)
    },
    
    /**
     * 显示分享成功
     */
    showShareSuccess() {
      this.$refs.successPopup.open()
    },
    
    /**
     * 关闭成功提示
     */
    closeSuccess() {
      this.$refs.successPopup.close()
    },
    
    /**
     * 检查是否在微信环境
     */
    isWechat() {
      // #ifdef H5
      return /micromessenger/i.test(navigator.userAgent)
      // #endif
      return false
    },
    
    /**
     * 显示成功提示
     */
    showSuccess(message) {
      uni.showToast({
        title: message,
        icon: 'success'
      })
    },
    
    /**
     * 显示错误提示
     */
    showError(message) {
      uni.showToast({
        title: message,
        icon: 'none'
      })
    },
    
    /**
     * 显示提示
     */
    showTip(message) {
      uni.showModal({
        title: '提示',
        content: message,
        showCancel: false
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.invite-share-container {
  // 容器样式
}

.share-popup {
  background: white;
  border-radius: 24rpx 24rpx 0 0;
  padding: 40rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 40rpx;
  padding-bottom: 20rpx;
  border-bottom: 1rpx solid #e0e0e0;
}

.popup-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.popup-close {
  font-size: 48rpx;
  color: #666;
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.invite-code-section {
  margin-bottom: 40rpx;
}

.code-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 16rpx;
}

.code-display {
  display: flex;
  align-items: center;
  background: #f8f9ff;
  border-radius: 12rpx;
  padding: 24rpx;
}

.code-text {
  flex: 1;
  font-size: 32rpx;
  font-weight: bold;
  color: #667eea;
  letter-spacing: 2rpx;
}

.copy-code-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 8rpx;
  padding: 12rpx 24rpx;
  font-size: 24rpx;
}

.qr-code-section {
  text-align: center;
  margin-bottom: 40rpx;
}

.qr-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.qr-code {
  width: 300rpx;
  height: 300rpx;
  border-radius: 12rpx;
  margin-bottom: 16rpx;
}

.qr-tip {
  font-size: 24rpx;
  color: #666;
}

.share-options {
  margin-bottom: 40rpx;
}

.options-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 24rpx;
}

.options-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 24rpx;
}

.option-item {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 24rpx;
  background: #f8f9fa;
  border-radius: 12rpx;
  transition: all 0.3s ease;
  
  &:active {
    background: #e9ecef;
    transform: scale(0.95);
  }
}

.option-icon {
  font-size: 40rpx;
  margin-bottom: 12rpx;
}

.option-label {
  font-size: 24rpx;
  color: #333;
}

.share-preview {
  border-top: 1rpx solid #e0e0e0;
  padding-top: 32rpx;
}

.preview-title {
  font-size: 28rpx;
  color: #333;
  margin-bottom: 20rpx;
}

.preview-content {
  background: #f8f9fa;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 20rpx;
}

.preview-text {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 12rpx;
}

.preview-desc {
  font-size: 26rpx;
  color: #666;
  line-height: 1.5;
  margin-bottom: 16rpx;
}

.preview-link {
  font-size: 24rpx;
  color: #667eea;
  word-break: break-all;
}

.copy-content-btn {
  width: 100%;
  background: #52c41a;
  color: white;
  border: none;
  border-radius: 12rpx;
  padding: 24rpx;
  font-size: 28rpx;
}

.success-popup {
  background: white;
  border-radius: 16rpx;
  padding: 60rpx 40rpx;
  text-align: center;
  min-width: 500rpx;
}

.success-icon {
  font-size: 80rpx;
  margin-bottom: 24rpx;
}

.success-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 16rpx;
}

.success-desc {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 40rpx;
  line-height: 1.5;
}

.success-btn {
  background: #667eea;
  color: white;
  border: none;
  border-radius: 50rpx;
  padding: 20rpx 60rpx;
  font-size: 28rpx;
}
</style>
